package com.orangelife.mobile.main.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.jump.CommonJumper;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.lookRepair.adapter.LookForRepairListAdapter;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.ToastHelper;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 维修订单
 * Created by yw on 2015/11/25.
 */
public class RepairFragment extends Fragment {
    View view;
    @Bind(R.id.lv_discount)
    PullToRefreshListView lvList;
    @Bind(R.id.tvNoBill)
    TextView tvNoBill;
    @Bind(R.id.llPropertyBillN)
    RelativeLayout llPropertyBillN;
    private Dialog dialog;
    private LookForRepairListAdapter<Map<String, Object>> adapter;
    private List<Map<String, Object>> list;
    private List<Map<String, Object>> list2;
    private Handler mHandler;
    private RepairHandler repairHandler;
    /**
     * 分辨是刷新还是加载更多
     */
    private int flags = 1;
    /**
     * 一页中数据的条数，初始设置为7条
     */
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    /**
     * 初始页，初始化为第一页
     */
    private int pageNo = Constant.PAGE_NO_DEFAULT;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (view == null)
            view = inflater.inflate(R.layout.fragment_repair_list, null, false);
        ButterKnife.bind(this, view);
        findView();
        getRepairList(pageSize, pageNo);
        return view;
    }

    private void findView() {
        tvNoBill.setText("您目前没有订单");
        mHandler = new Handler();
        getDataFromServer();
        pageNo = 1;
        setAdapter();
        lvList.setPullLoadEnable(false);
        lvList.setAdapter(adapter);
        pullListView();

        llPropertyBillN.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDataFromServer();
                getRepairList(Constant.PAGE_SIZE_DEFAULLT, Constant.PAGE_NO_DEFAULT);
            }
        });
    }


    /**
     * 设置适配器
     */
    private void setAdapter() {
        list = new ArrayList<>();
        list2 = new ArrayList<>();
        adapter = new LookForRepairListAdapter<>(getActivity(),
                list);
        adapter.setAdapterListener(new LookForRepairListAdapter.AdapterListenter() {

            @Override
            public void refresh(String str) {
                flags = 1;
                pageNo = 1;
                getRepairList(pageSize, pageNo);
            }
        });
        lvList.setPullLoadEnable(false);
        lvList.setAdapter(adapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        getRepairRead();
    }

    /**
     * 下拉刷新列表
     */
    private void pullListView() {
        lvList.setXListViewListener(new PullToRefreshListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // list.clear();
                        flags = 1;
                        pageNo = 1;
                        getRepairList(pageSize, pageNo);
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        flags = 0;
                        pageNo += 1;
                        getRepairList(pageSize, pageNo);
                        onLoad();
                        if (list != null) {
                            adapter.setList(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, 2000);
            }
        });
    }

    /**
     * 判断是否有订单显示无订单页面
     *
     * @param havebill
     */
    private void isNoBill(boolean havebill) {
        if (havebill) {
            lvList.setVisibility(View.VISIBLE);
            llPropertyBillN.setVisibility(View.GONE);
        } else {
            lvList.setVisibility(View.GONE);
            llPropertyBillN.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 刷新 拉下列表
     *
     * @param list2
     */
    private void updateListView(List<Map<String, Object>> list2) {
        boolean havebill = false;
        if (list2 == null) {
            lvList.setPullLoadEnable(false);
            if (flags == 1) {
                list.clear();
                adapter.setList(list);
                adapter.notifyDataSetChanged();
                havebill = false;
            }
        }
        if (list2 != null && list != null) {
            if (list2.size() == 0) {
                if (flags == 1) {
                    list.clear();
                    if (lvList != null)
                        lvList.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = false;
                } else {
                    lvList.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                }
            } else {
                if (flags == 1) {
                    list.clear();
                    lvList.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                } else {
                    lvList.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                }
            }
        } else {
            lvList.setPullLoadEnable(false);
            if (flags == 1) {
                havebill = false;
            }
        }
        isNoBill(havebill);
    }


    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(getActivity(),
                Constant.LOADING);
        dialog.show();
    }

    /**
     * 获取列表数据
     *
     * @param pageSize 每页的条数
     * @param pageNo   初始页
     */
    private void getRepairList(int pageSize, int pageNo) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", pageNo);
        map.put("pageSize", pageSize);
        Map<String, Object> rootMap = new HashMap<>();
        rootMap.put("map", map);
        rootMap.put("url", Constant.URL_LOOKREAPIR_LIST);
        rootMap.put("wat", 0);
        if (repairHandler == null) {
            repairHandler = new RepairHandler(this);
        }
        new JSONRequest(JSONRequest.POST, rootMap, repairHandler, HttpUtil.ACTION_JSON);
    }

    /**
     * 处理获得的数据
     */
    static class RepairHandler extends Handler {

        private WeakReference<RepairFragment> wr;

        public RepairHandler(RepairFragment fragment) {
            wr = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            RepairFragment fragment = wr.get();
            if (fragment != null) {
                switch (msg.what) {
                    case 0:
                        fragment.list2 = JsonReponseHandler.getListFromJson(
                                String.valueOf(msg.obj), fragment.adapter, fragment.dialog);

                        fragment.updateListView(fragment.list2);
                        break;
                    case 4:
                        String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                                .get("errInfo").toString();
                        if (errInfo.equals("OK")) {
                            Log.e("errInfo", "success");
                        } else {
                            Log.e("errInfo", "fail");
                        }
                        break;
                    case 500:
                        DialogHelper.closeDialog(fragment.dialog);
                        ToastHelper.getInstance()._toast(
                                msg.obj.toString());
                        break;
                    case 1011:
                        DialogHelper.closeDialog(fragment.dialog);
                        CommonJumper.jumpToLoginWhenExitWithClear(fragment.getActivity());
                        fragment.getActivity().finish();
                        break;

                    default:
                        break;
                }
            }
        }

    }

    ;


    @SuppressWarnings("deprecation")
    private void onLoad() {
        lvList.stopRefresh();
        lvList.stopLoadMore();
        lvList.setRefreshTime(new Date().toLocaleString());
    }

    /**
     * 维修列表消息状态改为已读
     */
    private void getRepairRead() {
        Map<String, Object> map = new HashMap<String, Object>();
        if (repairHandler == null) {
            repairHandler = new RepairHandler(this);
        }
        JSONRequest.getInstance().sendRequest(JSONRequest.GET, Constant.URL_REPAIR_READ, map, repairHandler, 4, HttpUtil.ACTION_URI);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
